package ink.xiaobaibai.units;

import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.token.JWTAuthenticationToken;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Set;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-05-31
 **/

public class MySecurity {

    public static Integer getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return null;
        }
        JWTAuthenticationToken authenticationToken = (JWTAuthenticationToken) authentication;
        return authenticationToken.getUserId();
    }

    public static String getUserNumber() {
        JWTAuthenticationToken authenticationToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return authenticationToken.getUserNumber();
    }

    public static String getRole() {
        JWTAuthenticationToken authenticationToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return authenticationToken.getRole();
    }

    public static Set<String> getRoles() {
        JWTAuthenticationToken authenticationToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return authenticationToken.getRoles();
    }

    public static String getJWT() {
        JWTAuthenticationToken authenticationToken = (JWTAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return authenticationToken.getJWT();
    }

    public static boolean isPower(String needRole) {
        if (getRole().equals(MyRole.ADMIN)) {
            return true;
        }
        return getRoles().contains(needRole);
    }

}
